import 'dart:convert';
import 'dart:io';
import 'package:dio/adapter.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/material.dart';
import 'package:blinkid_flutter/microblink_scanner.dart';
import 'package:barcode_scan/barcode_scan.dart';
import 'package:flutter/services.dart';
import 'package:dio/dio.dart';
import 'Util.dart';
import 'card2.dart';
import 'input.dart';
import 'result.dart';

class MyHome2Page extends StatefulWidget {
  MyHome2Page({Key key, this.title,this.para}) : super(key: key);
  final String title;
  final Map<String,dynamic> para;
  @override
  _MyHomePageState2 createState() => _MyHomePageState2();
}

class _MyHomePageState2 extends State<MyHome2Page> {
  Map<String,dynamic> buildings = {};
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    print(this.widget.para);
  }
  realPush2(qr){
    String block_key = widget.para["block_key"];
    Map<String, String> dic = {
      "api_key": "xQITe6bZFUrmeJbkcKgkUzajUI6FGLA",
      "block_key": block_key,
      "visitor_key": qr,
      "lang": "en"
    };
    Navigator.push( context, MaterialPageRoute(builder: (context) => ResultPage(title: widget.title,para: dic)),);
  }
  /// 扫描二维码
  Future scan2() async {
    if (ShareHandle.instance.shouldUseCamara){
      var result = await BarcodeScanner.scan();
      if (result.type == ResultType.Barcode) {
        showDialog<Null>(
            context: context,
            barrierDismissible: false,
            builder: (BuildContext context) {
              return new AlertDialog(
                title: new Text(result.rawContent),
                //可滑动
                content: new SingleChildScrollView(
                  child: new ListBody(
                    children: <Widget>[
                      new Text(''),
                    ],
                  ),
                ),
                actions: <Widget>[
                  new FlatButton(
                    child: new Text('确定'),
                    onPressed: () {
                      Navigator.of(context).pop();
                      realPush2(result.rawContent);
                    },
                  ),
                  new FlatButton(
                    child: new Text('取消'),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                ],
              );
            });
      }

      print(result.type); // The result type (barcode, cancelled, failed)
      print(result.rawContent); // The barcode content
      print(result.format); // The barcode format (as enum)
      print(result
          .formatNote); // If a unknown format was scanned this field contains a note
    }else{
      realPush2("wQIXKvSOGB/wMpLxW6QPXg2oVb6ZLbadrczYCzOYEzy3vxfTpi+BVkDf//HOLFNgTXVD9Nc0nkwBXL9AT0IJsjmdtH85vxo9N2Dnn5xQCcYKz/rn0v36");
    }
  }
  realPush(dic){
    Navigator.push( context, MaterialPageRoute(builder: (context) => Card2Page(title: "${buildings["estate_name"] ?? ""}${buildings["block"] ?? ""}",para: dic)),);
  }
  ///扫描证件
  Future<void> scan() async {
    if (ShareHandle.instance.shouldUseCamara){

      List<RecognizerResult> results;

      Recognizer recognizer = BlinkIdRecognizer();
      OverlaySettings settings = BlinkIdOverlaySettings();
      // set your license
      String license = "";
      if (Theme
          .of(context)
          .platform == TargetPlatform.iOS) {
        license = "sRwAAAESY29tLnNvdXJjZS52aXNpdG9yBj7d8v2R/vwEN2Uc+skOzyMQfFNF2MDxCaSHoOypPZH+sJusIbfn1b4Nw8uAiOYWuOuR3ZEQdappBixFIyfr34OGp8SEnpZYw5BOFj9kT+2Ix4QraA4iYde5Y7hqgcset6ULC0klnFo3vmQVfsIVzbkApG0nndheFnFviek3npQKATA9mCLkADClsBywDbhfkCTws+g4zasI1TKUcDxhWKxntnDANhgKVUvqE+cd6BLkKelprW1I5AcrZiI3+WFEN9a+DDGSa6Mf";
      } else if (Theme
          .of(context)
          .platform == TargetPlatform.android) {
        license = "sRwAAAASY29tLnNvdXJjZS52aXNpdG9yPkHiFsnZcfXltk9+iCuI1ZzCanIxaS2US2bx8YcLUi8W8Z1ZYtTAkQ0J1Q6Uun3C7QN1PW0/PyTeDxK0pdHujV03vTpT1KKShpbl5KjVfcX4mvj3CoNrdvuanwbCwBCz08qC62NJiR2rorF0GWDUPGp0PkjFtD0cIW/3OWdy4weu93+vSqKrl/UmAqCjkEYmwPU16y3xv0+F8aOeAFN4XshAa+iDWvt2jkDY6w2isTS/rWa6Qs4Hm8w6ZNUp//FZgW7b4kKVWbxR";
      }

      try {
        print("abc1");
        // perform scan and gather results
        results = await MicroblinkScanner.scanWithCamera(
            RecognizerCollection([recognizer]), settings, license);
        print("abc2");
        print(results);
        var cardid = "";
        var name = "";
        for (BlinkIdRecognizerResult x in results){
          print("abc3");
          print(x.toJson());
          print(x.classInfo.country);
          print(x.classInfo);
          print(x.fullName);
          print(x.personalIdNumber);
          print(x.sex);
          if (x.personalIdNumber.isNotEmpty){
            cardid = x.personalIdNumber;
          }
          if (x.fullName.isNotEmpty){
            name = x.fullName;
          }
        }
        var dic = this.widget.para;
        dic["id_no"] = cardid;
        dic["id_type"] = 1;
        dic["gender"] = 1;
        dic["visitor_name"] = name;
        realPush(dic);
      } on PlatformException {
        // handle exception
        print("abc4");
      }
      print("abc5");
    }else{
      var dic = this.widget.para;
      dic["id_no"] = "";
      dic["id_type"] = 1;
      dic["gender"] = 1;
      dic["visitor_name"] = "";
      realPush(dic);
    }
  }
  @override
  Widget build(BuildContext context) {
    SharedPreferences.getInstance().then((value){
//      print(json.decode(value.getString("buildings")));
//      print(value.getString("buildings").toMap());
      setState(() {
        buildings = value.getString("buildings").toMap();
      });
    });
    return Scaffold(
      body: Row(
        children: <Widget>[
          Expanded(
            child: Image(
              fit: BoxFit.cover,
              image: AssetImage("assets/images/login_bg01.png"),
            ),
          ),
          Expanded(
              child: Container(
            color: Color.fromARGB(255, 58, 58, 58),
            child: Stack(
              children: <Widget>[
                Container(
                  alignment: Alignment.topRight,
                  child: FloatingActionButton(
                    child: const Icon(Icons.settings),
                    onPressed: () {
                      Navigator.of(context).pushNamed("page2");
                    },
                  ),
                  padding: const EdgeInsets.all(20.0),
                ),
                Align(
                  child: Text(
                    "V 1.0",
                    style: TextStyle(color: Colors.white),
                  ),
                  alignment: Alignment.bottomCenter,
                ),
                Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Text(
                        "${buildings["estate_name"] ?? ""}${buildings["block"] ?? ""}",
                        style: TextStyle(fontSize: 18, color: Colors.white),
                      ),
                      SizedBox(height: 20),
                      Image(
                        image:
                            AssetImage("assets/images/login_icon_visitor.png"),
                      ),
                      SizedBox(height: 20),
                      Text(
                        "訪客記錄",
                        style: TextStyle(fontSize: 23, color: Colors.white),
                      ),
                      SizedBox(height: 20),
                      MaterialButton(
                        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        height: 40,
                        minWidth: 200,
                        padding: EdgeInsets.all(0),
                        color: Color(0xff4a701e),
                        textColor: Colors.white,
                        shape: RoundedRectangleBorder(
                            borderRadius:
                                BorderRadius.all(Radius.circular(10))),
                        onPressed: scan,
                        child: Text("掃描證件"),
                      ),
                      SizedBox(height: 20),
                      MaterialButton(
                        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        height: 40,
                        minWidth: 200,
                        padding: EdgeInsets.all(0),
                        color: Color(0xff4a701e),
                        textColor: Colors.white,
                        shape: RoundedRectangleBorder(
                            borderRadius:
                                BorderRadius.all(Radius.circular(10))),
                        onPressed: () {
                          Navigator.push( context, MaterialPageRoute(builder: (context) => InputPage(title: "${buildings["estate_name"] ?? ""}${buildings["block"] ?? ""}",para: this.widget.para)),);
                        },
                        child: Text("手動輸入個人資料"),
                      ),
                      SizedBox(height: 20),
                      MaterialButton(
                        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        height: 40,
                        minWidth: 200,
                        padding: EdgeInsets.all(0),
                        color: Color(0xff4a701e),
                        textColor: Colors.white,
                        shape: RoundedRectangleBorder(
                            borderRadius:
                                BorderRadius.all(Radius.circular(10))),
                        onPressed: scan2,
                        child: Text("掃描訪客二維碼"),
                      )
                    ],
                  ),
                )
              ],
            ),
          )),
        ],
      ),
    );
  }
}
